package org.cloud.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.cloud.apis.AccountFeignApi;
import org.cloud.apis.StorageFeignApi;
import org.cloud.mapper.PayOrderMapper;
import org.cloud.model.entity.PayOrder;
import org.cloud.service.IPayOrderService;
import org.springframework.stereotype.Service;

/**
 * ClassName: PayServiceImpl
 * Package: org.cloud.service.Impl
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2024/4/15 - 21:22
 * @Version: v1.0
 */
@Slf4j
@Service
public class PayServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Resource
    private PayOrderMapper orderMapper;

    /**
     * 订单微服务通过OpenFeign去调用库存微服务
     */
    @Resource
    private StorageFeignApi storageFeignApi;

    /**
     * 订单微服务通过OpenFeign去调用账户微服务
     */
    @Resource
    private AccountFeignApi accountFeignApi;


    @Override
    public void create(PayOrder order) {

        //xid检查
        String xid = RootContext.getXID();

        //1. 新建订单
        log.info("==================>开始新建订单"+"\t"+"xid_order:" +xid);
        //订单状态status：0：创建中；1：已完结
        order.setStatus(0);
        int result = orderMapper.insert(order);

        //插入订单成功后获得插入mysql的实体对象
        PayOrder orderFromDB = null;
        if(result > 0)
        {
            QueryWrapper<PayOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("status", order.getStatus());
            orderFromDB = orderMapper.selectOne(wrapper);
            //orderFromDB = orderMapper.selectByPrimaryKey(order.getId());
            log.info("-------> 新建订单成功，orderFromDB info: "+orderFromDB);
            System.out.println();
            //2. 扣减库存
            log.info("-------> 订单微服务开始调用Storage库存，做扣减count");
            storageFeignApi.decrease(orderFromDB.getProductId(), orderFromDB.getCount());
            log.info("-------> 订单微服务结束调用Storage库存，做扣减完成");
            System.out.println();
            //3. 扣减账号余额
            log.info("-------> 订单微服务开始调用Account账号，做扣减money");
            accountFeignApi.decrease(orderFromDB.getUserId(), orderFromDB.getMoney());
            log.info("-------> 订单微服务结束调用Account账号，做扣减完成");
            System.out.println();
            //4. 修改订单状态
            //订单状态status：0：创建中；1：已完结
            log.info("-------> 修改订单状态");
            orderFromDB.setStatus(1);
            int updateResult = baseMapper.updateById(orderFromDB);

            log.info("-------> 修改订单状态完成"+"\t"+updateResult);
            log.info("-------> orderFromDB info: "+orderFromDB);
        }
        System.out.println();
        log.info("==================>结束新建订单"+"\t"+"xid_order:" +xid);
    }
}
